﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace System
{
    /// <summary>
    /// 运行时间计数器
    /// </summary>
    public class MethodTimeWatch
    {
        DateTime _StartDate = DateTime.Now;
        int _OffSet = 0;
        public MethodTimeWatch()
        {
            //StackTrace st = new StackTrace();
            //StackFrame sf = st.GetFrames()[1];
            //int line = sf.GetFileLineNumber();
            //if(line==0)
            //{
            //    _OffSet = sf.GetILOffset();
            //}
        }

        /// <summary>
        /// 计时
        /// </summary>
        [Obsolete("无法精准获取行号")]
        internal void Record()
        {
            StackTrace st = new StackTrace();
            StackFrame sf = st.GetFrames()[1];
            int line = 0;
            if (_OffSet > 0)
            {
                line = sf.GetILOffset() - _OffSet;
            }
            else
            {
                line = sf.GetFileLineNumber();
            }
            string method = sf.GetMethod().Name;
            Record(string.Format("{0} {1}", method, line));
        }

        /// <summary>
        /// 计时
        /// </summary>
        /// <param name="expression">距离上一次计时所运行过的表达式</param>
        public void Record(string expression)
        {
            _Records[expression] = (DateTime.Now - _StartDate).TotalMilliseconds.ToString();
            _StartDate = DateTime.Now;
        }

        /// <summary>
        /// 计时
        /// </summary>
        /// <param name="expression">距离上一次计时所运行过的表达式</param>
        public void Record(int line)
        {
            Record(line.ToString());
        }


        NameValueCollection _Records = new NameValueCollection();

        /// <summary>
        /// 获取结果
        /// </summary>
        /// <returns></returns>
        public NameValueCollection GetRecords()
        {
            return _Records;
        }
    }
}
